<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.query.hostname" class="filter-item" placeholder="hostname（机器名称）" style="width: 200px;" @keyup.enter.native="filter" />
      <el-input v-model="listQuery.query.ip" class="filter-item" placeholder="IP 地址" style="width: 200px;" @keyup.enter.native="filter" />
      <el-button class="filter-item" icon="el-icon-search" style="margin-left: 10px;" type="primary" @click="filter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
    >
      <el-table-column prop="id" align="center" label="id" width="95px" sortable>
        <template v-slot="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="`desc`" sortable width="200px">
        <template v-slot="{row}">
          {{ row.desc }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="hostname（机器名称）" prop="hostname" sortable width="200px">
        <template v-slot="{row}">
          {{ row.hostname }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="IP 地址" prop="ip" width="200px" sortable>
        <template v-slot="{row}">
          {{ row.ip }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="运行系统" prop="system_type" width="100px" sortable>
        <template v-slot="{row}">
          {{ getSystemTypeName(row.systemType) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="工作目录" align="center">
        <template v-slot="{row}">
          {{ row.workDir }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150px">
        <template v-slot="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">修改</el-button>
          <el-button type="danger" size="mini" @click="del(row, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="listQuery.totalRecords>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.pageNum" :total="listQuery.totalRecords" @pagination="fetchData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="700px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="120px">
        <el-form-item prop="systemType">
          <template slot="label">
            <span>运行系统</span>
            <el-tooltip placement="top" content="压力机的操作系统类型，不同系统的连接方式会有不同"><i class="el-icon-question" style="margin-left: 3px;" /></el-tooltip>
          </template>
          <el-select v-model="form.systemType" placeholder="请选择运行系统" style="width:100%">
            <el-option
              v-for="item in systemTypeOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="desc">
          <template slot="label">
            <span>描述</span>
            <el-tooltip placement="top" content="这里可以输入一个更容易记住名字，后续选择压力机的时候会展示这个字段"><i class="el-icon-question" style="margin-left: 3px;" /></el-tooltip>
          </template>
          <el-input v-model="form.desc" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item prop="hostname">
          <template slot="label">
            <span>hostname</span>
            <el-tooltip placement="top" content="压力机的机器名称，连接压力机成功后会自动更新此字段"><i class="el-icon-question" style="margin-left: 3px;" /></el-tooltip>
          </template>
          <el-input v-model="form.hostname" placeholder="请输入 hostname（机器名称）" />
        </el-form-item>
        <el-form-item prop="ip">
          <template slot="label">
            <span>HOST / IP</span>
            <el-tooltip placement="top" content="需要登录压力机的 HOST 或 IP"><i class="el-icon-question" style="margin-left: 3px;" /></el-tooltip>
          </template>
          <el-input v-model="form.ip" placeholder="请输入 HOST / IP" />
        </el-form-item>
        <el-form-item prop="port">
          <template slot="label">
            <span>PORT</span>
            <el-tooltip placement="top" content="连接压力机的端口号"><i class="el-icon-question" style="margin-left: 3px;" /></el-tooltip>
          </template>
          <el-input v-model="form.port" maxlength="5" placeholder="请输入 PORT" />
        </el-form-item>
        <el-form-item prop="workDir">
          <template slot="label">
            <span>工作目录</span>
            <el-tooltip placement="top" content="压测脚本或环境的存放目录，不填则存放在用户的当前目录中"><i class="el-icon-question" style="margin-left: 3px;" /></el-tooltip>
          </template>
          <el-input v-model="form.workDir" placeholder="请输入 工作目录" />
        </el-form-item>
        <el-form-item prop="runCmd">
          <template slot="label">
            <span>预执行命令</span>
            <el-tooltip placement="top">
              <div slot="content" style="text-align: left">
                1. 登录服务器成功后需要先执行的命令<br>
                2. 比如登录后想切换到另一个用户等命令都可以写在这里
              </div><i class="el-icon-question" style="margin-left: 3px;" />
            </el-tooltip>
          </template>
          <el-input v-model="form.runCmd" placeholder="请输入登录成功后需要先执行的命令。例如：sudo su -" type="textarea" :rows="3" style="width: 100%" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.extra.isPasswordAuth" label="用户名 + 密码认证" name="passwordAuth" @change="passwordAuthChange" />
          <el-tooltip placement="top">
            <div slot="content" style="text-align: left">
              1. 认证方式可以用 用户名+密码，也可以用密钥文件免密登录<br>
              2. 当使用 用户名+密码 方式验证登录时，请勾选此选项
            </div><i class="el-icon-question" style="margin-left: 3px;" />
          </el-tooltip>
        </el-form-item>
        <el-form-item v-if="form.extra.isPasswordAuth" prop="extra.userName" label="用户名">
          <el-input v-model="form.extra.userName" placeholder="请输入登录 SSH 服务器的用户名" />
        </el-form-item>
        <el-form-item v-if="form.extra.isPasswordAuth" prop="extra.password" label="密码">
          <el-input v-model="form.extra.password" placeholder="请输入登录 SSH 服务器的密码" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.extra.isJumpServer" label="JumpServer 跳板机" name="passwordAuth" />
          <el-tooltip placement="top" content="当 HOST /IP 输入的是跳板机地址时，请勾选此选项"><i class="el-icon-question" style="margin-left: 3px;" /></el-tooltip>
        </el-form-item>
        <el-form-item v-if="form.extra.isJumpServer" prop="extra.serverIp">
          <template slot="label">
            <span>资产 IP</span>
            <el-tooltip placement="top">
              <div slot="content" style="text-align: left">
                1. 勾选 JumpServer 跳板机后就需要输入此字段，会在成功连接跳板机后自动连接此服务器<br>
                2. 请输入可访问的 IP 地址（例如，当主节点输入内网 IP，从节点又不在一个子网内，这样从节点将无法连接主节点，造成脚本运行失败）
              </div><i class="el-icon-question" style="margin-left: 3px;" />
            </el-tooltip>
          </template>
          <el-input v-model="form.extra.serverIp" placeholder="请输入登录 资产 IP" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?create():update()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, create, update, del } from '@/api/performance_test/generator'
import Pagination from '@/components/Pagination'
import { systemTypeOptions, getSystemTypeName } from '@/enum/systemType.js'
import { validIP, validPositiveInteger } from '@/utils/validate'

export default {
  components: { Pagination },
  data() {
    return {
      projectId: this.$store.getters.projectId,
      systemTypeOptions,
      list: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        totalRecords: 0,
        orders: undefined,
        query: {
          projectId: this.$store.getters.projectId
        }
      },
      form: {
        projectId: this.projectId,
        id: undefined,
        hostname: '',
        systemType: 1,
        extra: {
          isPasswordAuth: true,
          isJumpServer: true,
          userName: '',
          password: ''
        }
      },
      dialogFormVisible: false,
      formLabelWidth: '120px',
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {
        ip: [
          { required: true, message: '请输入 HOST / IP', trigger: 'change' },
          { max: 50, message: 'HOST / IP 长度不能超过 50 个字符', trigger: 'blur' }
        ],
        systemType: [
          { required: true, message: '请选择运行系统', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '请输入 描述', trigger: 'blur' },
          { max: 100, message: '描述 长度不能超过 100 个字符', trigger: 'blur' }
        ],
        port: [
          { required: true, message: '请输入 PORT', trigger: 'blur' },
          { validator: validPositiveInteger, message: 'PORT 只能输入正整数', trigger: 'blur' }
        ],
        'extra.userName': [
          { required: true, message: '请输入 用户名', trigger: 'blur' },
          { max: 50, message: '用户名 长度不能超过 50 个字符', trigger: 'blur' }
        ],
        'extra.password': [
          { required: true, message: '请输入 密码', trigger: 'blur' },
          { max: 50, message: '密码 长度不能超过 50 个字符', trigger: 'blur' }
        ],
        'extra.serverIp': [
          { required: true, message: '请输入 跳板机需要输入资产 IP', trigger: 'blur' },
          { validator: validIP, message: '请能输入正确的 IP 地址', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    getSystemTypeName,
    fetchData() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data.list
        this.listQuery.totalRecords = response.data.page.totalRecords
        this.listLoading = false
      })
    },
    filter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    // 创建
    create() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.extra = JSON.stringify(this.form.extra, null, 0)
          create(this.form).then(() => {
            this.dialogFormVisible = false
            this.$message({ message: '添加成功!', type: 'success' })
            this.fetchData()
          })
        }
      })
    },
    // 修改
    update() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.form.extra = JSON.stringify(this.form.extra, null, 0)
          update(this.form).then(() => {
            const index = this.list.findIndex(v => v.id === this.form.id)
            this.fetchData()
            this.list.splice(index, 1, this.form)
            this.dialogFormVisible = false
            this.$message({ message: '修改成功!', type: 'success' })
          })
        }
      })
    },
    resetForm() {
      this.form = {
        projectId: this.projectId,
        id: undefined,
        systemType: 1,
        port: 22,
        extra: {
          isPasswordAuth: true,
          isJumpServer: true,
          userName: '',
          password: ''
        }
      }
    },
    // 点击添加按钮
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 点击修改按钮
    handleUpdate(row) {
      this.form = Object.assign({}, row) // 复制行数据
      this.form.extra = JSON.parse(this.form.extra)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    del(row, index) {
      this.$confirm('是否删除此记录?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        del(row.id).then(response => {
          this.$message({ message: '删除成功!', type: 'success' })
          this.list.splice(index, 1)
        })
      })
    },
    // 点击 table 排序
    sortChange(column) {
      this.listQuery.orders = [{
        column: column.prop,
        asc: column.order === 'ascending'
      }]
      this.fetchData()
    },
    // 勾选或取消勾选 用户名+密码认证
    passwordAuthChange(val) {
      if (!val) {
        this.form.extra.userName = '' // 用户名
        this.form.extra.password = '' // 密码
      }
    }
  }
}
</script>
